<?php

    require_once('../inc/DBH.php');
    require_once('../inc/Session.php');
    require_once('../inc/Model/Usuario.php');

    $action = ( isset($_POST['action']) ? $_POST['action'] : null );

    if( ! $action ) echo '0';
    else {
        switch( $action ) {
            case 'login': handle_login(); break;
            case 'logout': handle_logout(); break;
            default: echo '0'; break;
        }
    }

    function handle_login() {
        $id   = ( isset($_POST['user_id'])   ? htmlentities($_POST['user_id'])   : null );
        $pass = ( isset($_POST['user_pass']) ? htmlentities($_POST['user_pass']) : null );

        if( ! ($id && $pass) ) {
            echo '0';
        } else {
            $user = Usuario::GetByID( $id );

            if( ! $user )                               echo '0';
            else if( $user->get_contrasena() != $pass ) echo '0';
            else if( open_session($id) ) echo '1';
            else                         echo '0';
        }
    }

    function handle_logout() {
        if( ! close_session() ) echo '0';
        else                    echo '1';
    }

?>